﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.IO;
using Ext.Net;
using Ext.Net.MVC;
using WebEntities;
using WebEntities.Models.WebInfo;
using com.subb.WebInformation;

namespace WebsiteAdmin.Controllers
{
    [Authorize]
    public class NewsController : Controller
    {
        private const string NEWSCOVER_PATH = "NewsCover/";
        private const string NEWSFILE_PATH = "NewsFile/";

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 新闻列表页面
        /// </summary>
        /// <param name="id">新闻目录ID</param>
        /// <returns></returns>
        public ActionResult NewsList(int id)
        {
            ViewBag.CataID = id;
            return View();
        }

        public ActionResult GetAllNewsByPage(int cataId, StoreRequestParameters parms, [ModelBinder(typeof(JsonModelBinder))]Dictionary<string, string>[] query)
        {
            WI_NewsCataDAL ncdal = new WI_NewsCataDAL();
            WI_NewsDAL ndal = new WI_NewsDAL();
            WI_NewsTypeDAL nydal = new WI_NewsTypeDAL();
            string findKey = string.Empty;
            if (query != null)
            {
                try
                {
                    findKey = query[0]["value"];
                }
                catch
                {
                    findKey = string.Empty;
                }
            }
            int ttlCount;
            List<WI_News> dbnewslist;
            if (cataId == 0)
            {
                dbnewslist = ndal.GetAllNews(parms.Start, parms.Limit, out ttlCount, findKey);
            }
            else
            {
                //检查NewsCata是否含有二级目录，如有，则获取下级目录的新闻列表
                List<WI_NewsCata> ncataList = ncdal.GetAllNewsCataByPcataId(cataId, 0, 100);
                if (ncataList.Count <= 0)
                {
                    //获取一级目录的新闻列表
                    dbnewslist = ndal.GetAllNews(cataId, parms.Start, parms.Limit, out ttlCount, findKey);
                }
                else
                {
                    //获取二级目录的新闻列表
                    dbnewslist = ndal.GetAllNewsByPCataID(cataId, parms.Start, parms.Limit, out ttlCount, findKey);
                }
            }
            List<News> newslist = new List<News>();
            foreach (var dbnews in dbnewslist)
            {
                //获取CataName
                string cataName = string.Empty;
                if (dbnews.CataID.HasValue)
                {
                    WI_NewsCata ncata = ncdal.GetNewsCata(dbnews.CataID ?? 0);
                    cataName = ncata.CataName;
                }
                //获取NewsType
                string ntypeName = string.Empty;
                if (dbnews.NewsType.HasValue)
                {
                    WI_NewsType ntype = nydal.GetNewsType(dbnews.NewsType ?? 0);
                    if (ntype != null)
                    {
                        ntypeName = ntype.TypeName;
                    }
                }
                News news = News.AsNews(dbnews, cataName, ntypeName);
                newslist.Add(news);
            }
            return this.Store(newslist, ttlCount);
        }

        public ActionResult GetAllNewsCata()
        {
            WI_NewsCataDAL ndal = new WI_NewsCataDAL();
            List<WI_NewsCata> dbcatalist = ndal.GetAllNewsCata();
            List<NewsCata> catalist = new List<NewsCata>();
            NewsCata cataAll = new NewsCata
            {
                CataID=0,
                CataName="全部"
            };
            catalist.Add(cataAll);
            foreach (var cata in dbcatalist)
            {
                //这里不需要显示RootCataName和ParentCataName，所以赋值为空
                NewsCata ncata = NewsCata.AsNewsCata(cata, "", "");
                catalist.Add(ncata);
            }
            return this.Store(catalist);
        }

        [HttpPost]
        public ActionResult DeleteNews(List<News> delNews)
        {
            try
            {
                WI_NewsDAL ndal = new WI_NewsDAL();
                foreach (var news in delNews)
                {
                    ndal.RemoveNews(news.NewsID);
                }
                return this.Direct(new { Success = true, Msg = "删除成功！" });
            }
            catch (Exception ex)
            {
                return this.Direct(new { Success = false, Msg = ex.InnerException != null ? ex.InnerException.Message : ex.Message });
            }
        }

        public ActionResult NewNewsWindow(int? cataId)
        {
            Window wnd = new Window()
            {
                ID = "Window1",
                Title = "新建新闻",
                Width = 700,
                Height = 500,
                Modal = true,
                Maximizable = true,
                Icon = Ext.Net.Icon.PageWhiteAdd,
                Loader = new ComponentLoader
                {
                    Url = Url.Action("CreateNews"),
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true,
                        Msg = "加载中，请稍候..."
                    }
                }
            };
            if (cataId.HasValue)
            {
                wnd.Loader.Params.Add(new Parameter("cataId", cataId.ToString()));
            }
            wnd.Render();
            return this.Direct();
        }

        public ActionResult NewsDescription(int? newsId)
        {
            if (newsId.HasValue && newsId.Value > 0)
            {
                WI_NewsDAL ndal = new WI_NewsDAL();
                WI_News winews = ndal.GetNews(newsId.Value, false);
                if (winews != null)
                {
                    string ndescr = Server.HtmlDecode(winews.Description);
                    ndescr = ndescr ?? string.Empty;
                    ndescr = ndescr.Replace("\r\n", "<br />");
                    ndescr = ndescr.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
                    ViewBag.NewsDescr = ndescr;
                }
            }
            return View();
        }

        public ActionResult CreateNews(int? cataId)
        {
            if (cataId.HasValue)
            {
                ViewData["CataID"] = cataId;
                WI_NewsCataDAL ncdal = new WI_NewsCataDAL();
                List<WI_NewsCata> cataList = ncdal.GetAllNewsCataByPcataId(cataId, 0, 100);
                //如果没有找到下级的新闻目录，就把自己加进新闻目录列表
                if (cataList.Count <= 0)
                {
                    WI_NewsCata ncata = ncdal.GetNewsCata(cataId ?? 0);
                    if (ncata != null)
                    {
                        cataList.Add(ncata);
                    }
                }
                ViewData["NewsCata"] = cataList;
                return View();
            }
            else
            {
                return View("CreateNews2");
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateNews(News news)
        {
            FormPanelResult response = new FormPanelResult();
            response.IsUpload = true;
            try
            {
                string ndescr = Server.HtmlEncode(news.Description);
                news.Description = ndescr;
                string creator = Request.IsAuthenticated ? HttpContext.User.Identity.Name : "Anonymous";
                news.Creator = creator;
                WI_NewsDAL ndal = new WI_NewsDAL();
                int newsId = ndal.CreateNews(news);
                //上传文件
                if (Request.Files.Count > 0)
                {
                    HttpFileCollectionBase fb = Request.Files;
                    HttpPostedFileBase fpfb1 = fb.Get("NewsCover");
                    HttpPostedFileBase fpfb2 = fb.Get("NewsFile");
                    string savePath = string.Empty;
                    //上传News封面图
                    if (fpfb1 != null && fpfb1.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + NEWSCOVER_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb1.FileName);
                            savePath += newsId + extName;
                            fpfb1.SaveAs(savePath);
                            //更新路径
                            string webpath = uploadVFolder + NEWSCOVER_PATH + newsId + extName;
                            News updNews = News.AsNews(ndal.GetNews(newsId, false), "", "");
                            updNews.NewsCover = webpath;
                            ndal.UpdateNews(newsId, updNews);
                        }
                    }
                    //上传News附件
                    if (fpfb2 != null && fpfb2.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + NEWSFILE_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb2.FileName);
                            savePath += "file-" + newsId + extName;
                            fpfb2.SaveAs(savePath);
                            //更新路径
                            string webpath = uploadVFolder + NEWSFILE_PATH + "file-" + newsId + extName;
                            News updNews = News.AsNews(ndal.GetNews(newsId, false), "", "");
                            updNews.NewsFile = webpath;
                            ndal.UpdateNews(newsId, updNews);
                        }
                    }
                }
                response.Success = true;
                response.ExtraParams.Add(new Parameter("Msg", "新闻创建成功！"));
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                return response;
            }
        }

        public ActionResult EditNewsWindow(int newsId)
        {
            Window wnd = new Window()
            {
                ID = "Window1",
                Title = "编辑新闻",
                Width = 700,
                Height = 480,
                Modal = true,
                Maximizable = true,
                Icon = Ext.Net.Icon.PageWhiteEdit,
                Loader = new ComponentLoader
                {
                    Url = Url.Action("EditNews"),
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true,
                        Msg = "加载中，请稍候..."
                    }
                }
            };
            wnd.Loader.Params.Add(new Parameter("newsId", newsId.ToString()));
            wnd.Render();
            return this.Direct();
        }

        public ActionResult EditNews(int newsId)
        {
            WI_NewsDAL ndal = new WI_NewsDAL();
            WI_News winews = ndal.GetNews(newsId, false);
            if (winews != null)
            {
                winews.Description = Server.HtmlDecode(winews.Description);
            }
            //这里不需要显示CataName，所以赋值为空
            News news = News.AsNews(winews, "", "");
            return View(news);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditNews(News news)
        {
            FormPanelResult response = new FormPanelResult();
            response.IsUpload = true;
            string ndescr = Server.HtmlEncode(news.Description);
            news.Description = ndescr;
            try
            {
                WI_NewsDAL ndal = new WI_NewsDAL();
                ndal.UpdateNews(news.NewsID, news);
                //上传文件
                if (Request.Files.Count > 0)
                {
                    HttpFileCollectionBase fb = Request.Files;
                    HttpPostedFileBase fpfb1 = fb.Get("NewsCoverFile");
                    HttpPostedFileBase fpfb2 = fb.Get("NewsFileUpload");
                    string savePath = string.Empty;
                    //上传News封面图
                    if (fpfb1 != null && fpfb1.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + NEWSCOVER_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb1.FileName);
                            savePath += news.NewsID + extName;
                            fpfb1.SaveAs(savePath);
                            //更新路径
                            string webpath = uploadVFolder + NEWSCOVER_PATH + news.NewsID + extName;
                            News updNews = News.AsNews(ndal.GetNews(news.NewsID, false), "", "");
                            updNews.NewsCover = webpath;
                            ndal.UpdateNews(news.NewsID, updNews);
                        }
                    }
                    //上传News附件
                    if (fpfb2 != null && fpfb2.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + NEWSFILE_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb2.FileName);
                            savePath += "file-" + news.NewsID + extName;
                            fpfb2.SaveAs(savePath);
                            //更新路径
                            string webpath = uploadVFolder + NEWSFILE_PATH + "file-" + news.NewsID + extName;
                            News updNews = News.AsNews(ndal.GetNews(news.NewsID, false), "", "");
                            updNews.NewsFile = webpath;
                            ndal.UpdateNews(news.NewsID, updNews);
                        }
                    }
                }
                response.Success = true;
                response.ExtraParams.Add(new Parameter("Msg", "新闻更新成功！"));
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                return response;
            }
        }
    }
}
